<template>
	<view>
		 <view class="djsNumber"  v-if="djsNumberDS">{{ countdown }}</view>
		<camera :device-position="device" :flash="flash" @error="error" :style="{ width: '100%',position: 'relative', height: getHeight + 'px' }">
			<cover-view class="topBox">
				
                <!-- 时间 -->
				
				<cover-view class="topItem">服务对象：{{userName}}</cover-view>
				<cover-view class="topItem">服务项目：{{serviceName}}</cover-view>
                <!-- 日期 -->
				<cover-view class="topItem">日期：{{nowTime}}</cover-view>
				<cover-view class="topItem">经度：{{jing}}</cover-view>
				<cover-view class="topItem">纬度：{{wei}}</cover-view>
                <!-- 地址 -->
				<cover-view class="topItem">地址：{{address}}</cover-view>
				<cover-view class="topItem">{{standard_address}}</cover-view>
				<!-- <cover-view class="topItem">备注：{{remarks}}</cover-view> -->
			</cover-view>
			<cover-image @click="dsdBtn" class="sgdImg" :src="dsUrl" style="bottom: 380px; width: 30px;right: 20px;">开启定时</cover-image>
            <!-- 旋转摄像头 -->
			<cover-image @click="xzBtn" class="xzImg" src="https://www.gxjiean.com:9000/java/35e0e22de9d28786d094224d0aecda275e272bc9b1b769b22346126520f46d28.png"></cover-image>
            <!-- 打开/关闭 闪关灯 -->
			<cover-image @click="sgdBtn" class="sgdImg" :src="sgdUrl"></cover-image>
			<!-- 打开/关闭 闪关灯 -->
			<!-- <cover-image @click="sgdBtn" class="sgdImg" :src="sgdUrl">上传</cover-image>
			 -->
            <!-- 拍照 -->
			<!-- <cover-view class="cameraBtn" @click="saveImageToGallery('https://www.gxjiean.com:9000/java/60063c128f7a14e91421bdab97ad92d0ed53b5902946231c0c52e792923b22c3.png')">
				<cover-view class="cameraBtn2"></cover-view>
			</cover-view> -->
			<cover-view class="cameraBtn" @click="takePhoto" v-if="takePhotoDisabled==0">
				<cover-view class="cameraBtn2"></cover-view>
			</cover-view>
			<cover-view class="cameraBtn"   v-else="takePhotoDisabled==1">
				<cover-view class="cameraBtn2"></cover-view>
			</cover-view>
          
            <!-- 底部预览生成图片 saveImageToGallery-->
			<cover-view class="bottomBg" v-if="imgList.length > 0">
				<cover-view>
					<cover-view @click="ViewImage(index)" class="imgBox" v-for="(item,index) in imgList" :key="index">
						<cover-image class="imgItem" :src="item.src" mode="aspectFill"></cover-image>
						<cover-view class="cu-tag" @tap.stop="DelImg" :data-index="index">
							<cover-image class="iconClose" src="https://www.gxjiean.com:9000/java/499db26e7792f86aba8aeb05192c4f79a5546d0f1f95e9cedfe340804223b899.png" mode="aspectFill"></cover-image>
						</cover-view>
					</cover-view>
				</cover-view>
				
				<cover-view class="shangc" @click="takePhotoSubmit">
					<cover-view >上传</cover-view>
				</cover-view>
			</cover-view>
		</camera>

        <!-- canvas元素，利用它的功能，实现添加水印 -->
		<view style="position: absolute;top: -999999px;">
          <view>
            <canvas :style="{ width: w, height: h }" canvas-id="firstCanvas"></canvas>
          </view>
		</view>

	</view>
</template>

<script>
	
	import QQMapWX from "@/static/qqmap-wx-jssdk";
	import { getCurrentInstance } from 'vue'  
	
	export default {
		name:"watermark-camera",
		props: {
			imgNumber: { // 上传图片的数量
				type: Number,
				default: 1
			},
			serviceName:{
				type: String,
				default: "未查询到服务"
			},
			userName:{
				type: String,
				default: "未查询到服务"
			},
			remarks:{
				type: String,
				default: "无"
			},
			imgLists:{
				type: Array,
				
			},
		},	
		data() {
		  return {
			  takePhotoDisabled:0,
			djsNumberDS:false,
		    getHeight: '200', // camera 组件高度
		    device: 'back', //前置或后置摄像头，值为front, back
		    flash: 'off', // 闪光灯，值为auto, on, off
		    nowTime: '2025-3-10 14:45', //日期
		    nowTime2: '2222', //时间
		    address: '未定位成功，请检查网络', //当前地址信息
			standard_address:"",
			jing:"未定位成功，请检查网络",
			wei:"未定位成功，请检查网络",
		    //sgdUrl: 'https://cdn.zhoukaiwen.com/sgd.png', // 闪光灯图片地址
			sgdUrl:"https://www.gxjiean.com:9000/java/c9aba0fe9f15575da326b82132ff8994200edf54a8491042d0934e704e0fa5bd.png",
		    imgList: [ // 底部预览图片的列表
		      /* {
		       	src: "https://cdn.zhoukaiwen.com/angular.jpg"
		       } */
		    ],
		    w: '', // canvas 元素宽度
		    h: '' ,// canvas 元素高度
			dsUrl:"https://www.gxjiean.com:9000/java/e167bc8e279fa55efd8959a687cfd9b4a235e994804a940f4e1d8159e383461f.png",
			countdown: 5, // 初始值设为5，你也可以根据需要调整初始值或逻辑
			timer: null, // 用于存储定时器的ID，以便之后可以清除它
		  }
		},

		created() {
			const that = this;
			
			uni.getSystemInfo({
				success: function(res) {
				  that.getHeight = res.windowHeight;
				}
			});
			this.getLocationadd()
			this.getTime()
			// this.imgUrls  = uni.getStorageSync('imageUrls');
		},
		onReady() {
			this.imgList=this.imgLists
			console.log("this.imgList:",this.imgList)
		},
		/* beforeDestroy() { // 或 beforeUnmount 在 Vue 3 中使用 composition API 时使用此生命周期钩子来清除定时器，避免内存泄漏。
		    if (this.timer) {
		      clearInterval(this.timer); // 清除定时器以避免内存泄漏
		    }
		}, */
		methods: {
			takePhotoSubmit(){
				this.$emit('takePhotoSubmit',this.imgList)
			},
			//获取定位地址
			getLocationadd(){
				let that = this;
				wx.getSetting({
				  success(res) {
				    if (res.authSetting['scope.userLocation'] == false){// 如果已拒绝授权，则打开设置页面
				      wx.openSetting({
				        success(res) {}
				      })
				    }  else { // 第一次授权，或者已授权，直接调用相关api
				      that.getMyLocation()
				    }
				  }
				})
			},
			// 获取当前地理位置
			getMyLocation(){
				let that = this;
				var qqmapsdk;
			   // 获取当前位置信息 
			     uni.getLocation({
			       type: 'gcj02',
			       success: function(res) {
			         console.log('当前位置的经度：' + res.longitude);
			         console.log('当前位置的纬度：' + res.latitude);
					 that.jing=res.longitude
					 that.wei=res.latitude
			         qqmapsdk = new QQMapWX({
			           key: "RENBZ-PIECC-XH726-A3CH7-ORIWF-QLB2D" //自己申请的腾讯地图key
			         });
			         // 根据经纬度反解析出地址名称
			         qqmapsdk.reverseGeocoder({
			           location: {
			             latitude: res.latitude,
			             longitude: res.longitude
			           },
			           success(addressRes) {
						 console.log('根据经纬度反解析出地址名称：' +JSON.stringify(addressRes));
						 that.address = addressRes.result.formatted_addresses.recommend;
						 that.standard_address = addressRes.result.formatted_addresses.standard_address;
			           },
			           fail(res) {}
			         });
			       }
			     });
			},
			
			  // 旋转摄像头
			xzBtn() {
			  if (this.device == 'front') {
			    this.device = 'back'
			  } else {
			    this.device = 'front'
			  }
			},
			// 打开/关闭 闪光灯
			sgdBtn() {
			  if (this.flash == 'off') {
			    this.flash = 'on'
			    this.sgdUrl = 'https://cdn.zhoukaiwen.com/sgd_on.png'
			  } else {
			    this.flash = 'off'
			    this.sgdUrl = 'https://cdn.zhoukaiwen.com/sgd.png'
			  }
			},
			//定时
			dsdBtn(){
				if (this.flash == 'off') {
				  this.flash = 'on'
				  this.djsNumberDS=true
				  this.dsUrl = 'https://www.gxjiean.com:9000/java/47b51df3733f3aca16db4fd4acff8abb72a452efa827f633cc551af2e506224f.png'
				  
				  this.countdown=5
				} else {
				  this.flash = 'off'
				  this.dsUrl = 'https://www.gxjiean.com:9000/java/e167bc8e279fa55efd8959a687cfd9b4a235e994804a940f4e1d8159e383461f.png'
				  this.djsNumberDS=false
				  this.countdown=5
				}
				//https://www.gxjiean.com:9000/java/98ba54bca62d27a7175ed79a46d84874294a5e3db6479044fd1f02440a976183.png
				//暂停
				//、https://www.gxjiean.com:9000/java/02cd06021bf33b67ea5e4d4bd5f8fe08619f1ecd4b11a190626cb0f0ef6934e3.png  
			},
			// 删除水印照片
			DelImg(e) {
			  uni.showModal({
			    content: '确定要删除这张照片吗？',
			    cancelText: '取消',
			    confirmText: '确认',
			    success: res => {
			      if (res.confirm) {
			        this.imgList.splice(e.currentTarget.dataset.index, 1)
			      }
			    }
			  })
			},
			// 查看照片
			ViewImage(index) {
			  const imgList = [this.imgList[index].src];
			  uni.previewImage({
			    urls: imgList
			  });
			},
			// startCountdown(){
			// 	 setTimeout(() => {
			// 	        //alert('5秒后执行');
			// 	      }, 5000); // 5000毫秒等于5秒
			// },
			 takePhoto(){
				   console.log("---------")
				   this.takePhotoDisabled=1;
			        if (this.imgList.length < this.imgNumber) {
						
						if(this.djsNumberDS){
							  
							   console.log("---------定时")
							   this.countdown=5
							   this.timer = setInterval(() => {
								 if (this.countdown > 0) {
								   this.countdown -= 1; // 每次调用减少1秒
								 } else {
								   clearInterval(this.timer); // 倒计时结束，清除定时器
									console.log("---------开始拍照")
									this.takePhoto2()
								   // 可以选择在这里显示数字或者做其他事情，例如：this.showNumber = true; this.countdown = 5;
								 }
							   }, 1000); // 每1000毫秒（1秒）更新一次
						}else{
								console.log("---------不定时")
								this.takePhoto2()
						}
					}else{
					   uni.showToast({
					     title: '最大上传'+this.imgNumber+'张照片!',
					     duration: 2000,
					     icon: 'none'
					   });
					    this.takePhotoDisabled=0
					}
			 },
			// 点击拍照
			takePhoto2() {
			  var that = this;
			  if (this.imgList.length < this.imgNumber) {
				  uni.showLoading({
				  	title: '生成水印中,请稍等...'
				  });
				   
				
			    // 创建并返回 camera 组件的上下文 cameraContext 对象
			    const ctx = uni.createCameraContext();
				 
			    // 拍照
			    ctx.takePhoto({
			      quality: 'low', // 图片质量高
			      success: (res) => {
			        var tempImagePath = res.tempImagePath; // 临时图片路径
			        // 获取图片信息
			        uni.getImageInfo({
			          src: res.tempImagePath,
			          success: ress => {
			            that.w = ress.width / 3 + 'px'; // 设置 canvas 元素宽度
			            that.h = ress.height / 3.01 + 'px'; // 设置 canvas 元素高度
						
			            let ctx = uni.createCanvasContext('firstCanvas',this); /** 创建画布 */
			            //将图片绘制到cancas内
			            ctx.drawImage(res.tempImagePath, 0, 0, ress.width / 3, ress.height / 3);
			            
			            ctx.setFontSize(12); // 设置字体大小为 10px
			            ctx.setFillStyle('#FFFFFF'); // 设置颜色为白色
			            
			            let textToWidth = (ress.width / 3) * 0.03; // 绘制文本的左上角x坐标位置
						 let textToHeight = (ress.height / 3) * 0.63; // 绘制文本的左上角y坐标位置
			            let textToHeight1 = (ress.height / 3) * 0.68; // 绘制文本的左上角y坐标位置
			            let textToHeight2 = (ress.height / 3) * 0.75;
						 let textToHeight3 = (ress.height / 3) * 0.80;
						 let textToHeight4 = (ress.height / 3) * 0.85;
						 let textToHeight5 = (ress.height / 3) * 0.90;
						 let textToHeight6 = (ress.height / 3) * 0.95;
			            
			            // 绘制日期和时间
			           /* ctx.fillText(that.nowTime , textToWidth, textToHeight1);
			            // 绘制地址
			            ctx.fillText(that.address, textToWidth, textToHeight2);
						// 绘制地址
						ctx.fillText(that.standard_address, textToWidth, textToHeight3); */
						that.canvasTextAutoLine(  ctx,"服务对象："+that.userName,textToWidth, textToHeight,200,15 )
						that.canvasTextAutoLine(  ctx,"服务项目："+that.serviceName,textToWidth, textToHeight1,200,15 )
						that.canvasTextAutoLine(  ctx,"经度："+that.jing,textToWidth, textToHeight2,200,15 )
						that.canvasTextAutoLine(  ctx,"纬度："+that.wei,textToWidth, textToHeight3,200,15 )
						that.canvasTextAutoLine(  ctx,"时间："+that.nowTime,textToWidth,textToHeight4,200,   15 )
						that.canvasTextAutoLine(  ctx,"地址："+that.address+">>"+that.standard_address,textToWidth,textToHeight5,200,   15 )
						
						
						
						// 文本集合
						

			            // 绘制完成后，在下一个事件循环将 canvas 内容导出为临时图片地址
			            ctx.draw(false, () => {
							console.log("返回",1)
			              setTimeout(() => {
			                uni.canvasToTempFilePath({
			                  canvasId: 'firstCanvas',
			                  success: res1 => {
								console.log("返回",res1.tempFilePath)
			                    /* tempImagePath = res1.tempFilePath
			                    that.imgList.push({
			                      src: tempImagePath
			                    })
								that.$emit('clickTakePhoto', {
									tempImagePath:tempImagePath,
									imgList:that.imgList
								}) */
								uni.compressImage({
									src: res1.tempFilePath,
									quality: 40,
									success: resImage => { 
										
										//res.tempFilePath} resImage.tempFilePath
								
								//图片上传
								let token = uni.getStorageSync("token");
								console.log("返回token",token)
								uni.uploadFile({
									url:this.http.httpsLian.upload, // 仅为示例，非真实的接口地址
									name: 'file', //必填 , 此为类型名称
									filePath: resImage.tempFilePath, //电子签名图片路径
									header: {
										'tenant-id': 1,
										//"content-type": "application/json",//"Content-Type": "multipart/form-data",
										"Authorization": "Bearer "+token
									},
									success: (res) => {   
										let data =JSON.parse(res.data)
										console.log('地址',data.data );
										
										//上传成功后逻辑
										//tempImagePath = res.data.data
										that.imgList.push({
										  src: data.data,
										  url: data.data
										})
										that.$emit('clickTakePhoto', {
											tempImagePath:data.data,
											imgList:that.imgList
										})
										that.saveImageToGallery(res1.tempFilePath)
										that.takePhotoDisabled=0
										uni.hideLoading();
										
									},
									fail: (err) => {
										console.log(err);
										uni.hideLoading();
										that.takePhotoDisabled=0
										uni.showToast({
											title: '上传失败!'
										});
									}
								},this);
								}
								})
			                  }
			                },this);
			              }, 200);
			            });
			          }
			        });
			      }
			    });
			  } else {
			    uni.showToast({
			      title: '最大上传'+this.imgNumber+'张照片',
			      duration: 2000,
			      icon: 'none'
			    });
			  }
			},
			//图片保存到手机
			saveImageToGallery(imageUrl) {
			    // 将下载的图片保存到相册
			    uni.saveImageToPhotosAlbum({
			        filePath: imageUrl,
			        success: function () {
			            console.log('保存成功');
			        },
			        fail: function (error) {
			            console.log('保存失败', error);
			        }
			    });
			},
			// 用户不允许使用摄像头时触发
			error(e) {
			  console.log(e.detail);
			},
			// 获取日期时间
			getTime: function() {
			  var date = new Date(),
			      year = date.getFullYear(),
			      month = date.getMonth() + 1,
			      day = date.getDate(),
			      hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
			      minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
			      second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			  month >= 1 && month <= 9 ? (month = "0" + month) : "";
			  day >= 0 && day <= 9 ? (day = "0" + day) : "";
			  var timer = year + '年' + month + '月' + day + '日';
			  var timer2 = hour + ':' + minute + ':' + second;
			  this.nowTime = timer+" "+timer2;
			 // this.nowTime2 = ;
			},
			/**
			 * canvas文本超出范围时，自动换行
			 * @param {*} ctx
			 * @param {*} text
			 * @param {*} x
			 * @param {*} y
			 * @param {*} maxWidth
			 * @param {*} lineHeight
			 */
			canvasTextAutoLine(ctx, text, x, y, maxWidth, lineHeight) {
			  let lineWidth = 0
			  let lastSubStrIndex = 0  
			  for (let i = 0; i < text.length; i++) {
			    lineWidth += ctx.measureText(text[i]).width
			    if (lineWidth > maxWidth) {
			      ctx.fillText(text.substring(lastSubStrIndex, i), x, y)
			      y += lineHeight
			      lineWidth = 0
			      lastSubStrIndex = i
			    }
			    if (i === text.length - 1) {
			      ctx.fillText(text.substring(lastSubStrIndex, i + 1), x, y)
			    }
			  }
			},
			


		}
	
	}
</script>

<style lang="scss" scoped>
	.djsNumber{
		 font-size: 120px;
		 position: absolute; /* 或 relative */
		 bottom: 300px;          /* 垂直居中 */
		// left: 100px;
		// right: 0;           /* 水平居中 */
		// margin: auto;       /* 需要同时设置top, bottom, left, right为0 */
		 z-index: 998;
		width: 100%;
		//height: 100%;
		
		//background-color: #007AFF;
		text-align: center;
		color: white;
	}
	.shangc{
		color: #00ac4e;
		font-size: 22px;
		padding-right: 25px;
	}
		.topBox {
			width: 750rpx;
			box-sizing: border-box;
			padding: 30rpx;
			color: #EEEEEE;
			font-size: 34rpx;
	
			.topItem {
				width: 100%;
				white-space: pre-wrap;
				margin-bottom: 15rpx;
			}
		}
	
		.cameraBtn {
			width: 120rpx;
			height: 120rpx;
			line-height: 120rpx;
			border: 6rpx #FFFFFF solid;
			border-radius: 50%;
			padding: 8rpx;
			position: absolute;
			left: calc(50% - 60rpx);
			bottom: 210rpx;
			 z-index: 999;
		}
	
		.cameraBtn2 {
			width: 100%;
			height: 100%;
			border-radius: 50%;
			background-color: #FFFFFF;
			text-align: center;
			color: #007AFF;
		}
	
		.xzImg {
			width: 52rpx;
			height: auto;
			position: absolute;
			right: 44rpx;
			bottom: 580rpx;
			 z-index: 999
		}
	
		.sgdImg {
			width: 40rpx;
			height: auto;
			position: absolute;
			right: 50rpx;
			bottom: 450rpx;
			 z-index: 999
		}
	
		.bottomBtn {
			width: 100%;
			height: 150rpx;
			padding-bottom: 15rpx;
			position: absolute;
			bottom: 0;
			left: 0;
			text-align: center;
			display: flex;
			justify-content: space-between;
			
			.btn {
				width: 30%;
				height: 150rpx;
				font-size: 34rpx;
				color: #FFFFFF;
				line-height: 150rpx;
			}
		}
	
		.bottomBg {
			width: 100%;
			height: 170rpx;
			box-sizing: border-box;
			padding: 20rpx 30rpx 40rpx;
			position: absolute;
			bottom: 0;
			left: 0;
			background-color: rgba(0, 0, 0, .8);
			display: flex;
			justify-content: space-between;
			align-items: center;
			z-index: 999;
			.imgBox {
				width: 110rpx;
				height: 110rpx;
				float: left;
				margin-right: 40rpx;
				position: relative;
	
				.cu-tag {
					position: absolute;
					right: 0;
					top: 0;
					border-bottom-left-radius: 2px;
					padding: 3px 5px;
					height: auto;
					background-color: rgba(0, 0, 0, 0.5);
					font-size: 10px;
					vertical-align: middle;
					font-family: Helvetica Neue, Helvetica, sans-serif;
					white-space: nowrap;
					color: #ffffff;
				}
			}
	
			.imgItem {
				width: 110rpx;
				height: 110rpx;
			}
		}
	
		.iconClose {
			width: 20rpx;
			height: 20rpx;
		}

</style>
